<template>
    <view class="content">
        <view class="top-bgc"></view>
        <view class="main">
            <view class="title">员工数字化</view>
            <view class="describe">新零售低成本、高效办公新方式</view>
        </view>
        <view class="bottom-bgc"></view>
    </view>
</template>
<script setup lang="ts" >
    import { defineComponent, ref, onMounted } from 'vue';
    import apps from '../app';
    import { onLoad } from "@dcloudio/uni-app";
    import { useMainStore } from '../../../store/modules/store';
    import { useLoginStore } from '../../../store/modules/useLoginStore';
    import { useModuleDataStore } from '@/store/useModuleDataStore';
    import service from '@/common/service';
    import permManager from '@/common/js/permission'
    const mainStore = useMainStore();
    const LoginStore = useLoginStore();
    const notificationStatus = ref(false);

    // 检查是否更新 版本号格式5.240615.00
    const VerUpdate = () => {
        const systemInfo = uni.getSystemInfoSync();
        let loaclVer = systemInfo.appWgtVersion;
        let newVer = "";
        apps.GetAppLastVesion({}, (AppVesion) => {
            if (AppVesion && AppVesion.ObjectData && AppVesion.ObjectData.length > 0 && AppVesion.ObjectData[0].c_version) {
                newVer = AppVesion.ObjectData[0].c_version;
                apps.setStorageSync('MBMAppVerion', newVer)
            }
            if (newVer && newVer.startsWith('5')) {
                const _newVer =  removeDotsAndConvertToNumber(newVer);
                const _loaclVer =  removeDotsAndConvertToNumber(loaclVer);
                if (newVer && _loaclVer < _newVer) {
                    const jsonString = JSON.stringify(AppVesion.ObjectData);
                    uni.navigateTo({
                        url: '../main/UpdateLog?data='+ encodeURIComponent(jsonString) + '&isUpdate=true'
                    });
                } else {
                    onlogin();
                }
            } else {
                onlogin();
            }
        }, () => {
            //请求异常时，重置设置客户代码。
            uni.reLaunch({
                url: '../reg/reg'
            });
        });

    };
    // 版本号转number格式
    const removeDotsAndConvertToNumber = (versionString: string) => {
      if (versionString) {
        const noDots = versionString.replace(/\./g, '');
        const number = parseInt(noDots, 10);
        return number;
      }
    };
    const onlogin = () => {
        let login_data = apps.getStorageSync('login_data');

        if (!login_data || !login_data.sUser || !login_data.sPassword) {
            bindLogin();
            return ''
        } else {
            login_data.sSerial=service.getDeviceInfo().deviceId;
            apps.MobileLoginNew(login_data, (res) => {
                if (res.HasException) {
                    if (res.Exception.Message) {
                        bindLogin();
                    }
                } else {
                    if (res.ObjectData) {
                        // let uniIdToken = LoginStore.token;
                        let uniIdToken = apps.getStorageSync('uniIdToken');
                        let loginInfo = res.ObjectData;
                        let Token = res.UserState;
						
						if(loginInfo.sWarning){
							uni.showModal({
								title: '提示',
								content: loginInfo.sWarning,
								confirmText:'确认',
								showCancel:false,
								success: function (res) {
									if (res.confirm) {
										try {
										    //自动登录后也需要重新设置localstorage
										    apps.addlocalStorage('$state', loginInfo);
										    apps.setStorageSync('$state', loginInfo);
										    apps.setStorageSync('uniIdToken', Token);
										    // LoginStore.setToken(res.UserState)
										    // TODO 待开发
										    if (uniIdToken) {
										    //     login();
										    }
										    mainStore.loginInfoin(loginInfo);
										        // TODO 待开发
										    // apps.setEnjoyServiceIp((data) => {
										    //     this.enjoyServiceIpin(data);
										    // });
										
										} catch (e) {}
										// #ifdef APP
										OperatePushReg(login_data.sUser);
										// #endif
										GetMyMenu();
										uni.reLaunch({
										    url: '../main/main',
										});
									}
								}
							});
						}else{
							try {
							    //自动登录后也需要重新设置localstorage
							    apps.addlocalStorage('$state', loginInfo);
							    apps.setStorageSync('$state', loginInfo);
							    apps.setStorageSync('uniIdToken', Token);
							    // LoginStore.setToken(res.UserState)
							    // TODO 待开发
							    if (uniIdToken) {
							    //     login();
							    }
							    mainStore.loginInfoin(loginInfo);
							        // TODO 待开发
							    // apps.setEnjoyServiceIp((data) => {
							    //     this.enjoyServiceIpin(data);
							    // });
							
							} catch (e) {}
							// #ifdef APP
							OperatePushReg(login_data.sUser);
							// #endif
							GetMyMenu();
							uni.reLaunch({
							    url: '../main/main',
							});
						}
                    }
                }
            }, () => {
                //请求异常时，也返回登录界面。
                bindLogin();
            });
        }
    };
    const bindLogin = () => {

        const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
        if (!CUSTOMEROBJECT) {
            uni.reLaunch({
                url: '../reg/reg'
            });
        } else {
            uni.reLaunch({
                url: '../login/login'
            });
        }
    };
    interface ICustInfo<T> {
        RowsCount: number;
        PageCount: number;
        CurrentPage: number;
        PageSize: number;
        ReturnObject: T[];
        [key: string]: any;
    };
    interface CustomerItem  {
        c_cloud_id: string;
        c_application: string;
        c_ismain_app: string;
        c_name: string;
        c_status: string;
        [key: string]: any;
    }

    const ReStoreCloudInfo = (CustInfo: any) => {
        // : ICustInfo<CustomerItem[]>): void
        let listObj = {
            EnjoyMain: null
        };

        if (CustInfo && CustInfo.ReturnObject && CustInfo.ReturnObject.length) {
            let ReturnObject = CustInfo.ReturnObject;
            for (let i in ReturnObject) {
                let item = ReturnObject[i];
                listObj.ID = item.c_cloud_id;
                if (item.c_ismain_app === "是") {
                    listObj.EnjoyMain = {
                        ...item,
                        c_mobile_service_ip: item.c_mobile_service_ip + '/mbmv5',
                    };
                }
                listObj[item.c_application] = {
                    ...item
                };
            }

            if (listObj.EnjoyMain) {
                service.setStorageSync("CUSTOMEROBJECT", listObj);
                LoginStore.setCustomer(listObj);
                VerUpdate();
            } else {
                uni.showToast({
                    duration: 3500,
                    icon: 'none',
                    title: '无主应用配置！'
                });

                uni.reLaunch({
                    url: '../reg/reg'
                });
            }
        } else {
            uni.showToast({
                duration: 3500,
                icon: 'none',
                title: '没有查询到客户代码！'
            });
            //未查询到客户代码时也返回的客户代码设置界面
            uni.reLaunch({
                url: '../reg/reg'
            });
        }
    };
    // 消息注册
    const OperatePushReg = (sUserNo) => {
        let info, ClientId = '',
            pushstr = '',
            sDeviceName = '',
            sDeviceTypeName = 'Android';
        let push = plus.push;
        // console.log('info-------------------------', JSON.stringify(info));
        if (push != undefined && push != '' && push != null) {
            info = push.getClientInfo();
        }

        if (info != undefined && info != '' && info != null) {
            ClientId = info.clientid;
        }
        //注册成功才处理
        if (ClientId) {
            sDeviceTypeName = plus.os.name != "iOS" ? 'Android' : 'IOS';
            //当两台ios设备使用相同apple账号时获取到的uuid是相同的，加上型号以区分
            sDeviceName = sDeviceTypeName == 'IOS' ? (plus.device.model + '&&' + plus.device.uuid) : plus.device.uuid;

            pushstr = 'device:' + JSON.stringify(plus.device) + 'os:' + JSON.stringify(plus.os) + 'ios：' + JSON.stringify(plus.ios);

            const ObjectData = {
                sUser: sUserNo,
                sMiPushID: ClientId,
                sDeviceType: sDeviceTypeName,
                sDeviceName: sDeviceName,
                sComment: pushstr,
                flag: 'auto',
                sSysRecStatus: (notificationStatus.value === false ? '暂停使用' :'') //若系统通知关闭后，则自动设置接收状态为暂停使用；若系统通知是开启的，则按管e通->我的中开启状态走。
            }
            apps.OperatePushReg(ObjectData, (res) => {
                if (res.HasException && res.Exception.Message) {
                    uni.showToast({
                        duration: 3500,
                        icon: 'none',
                        title: res.Exception.Message,
                        mask: true,
                    });
                }
            }, () => {
                //失败时忽略处理
            });
        }
    }
    onLoad(() => {
        //检查通知开关设置
        try {
            //未开启通知时是否提醒过了，只提醒一次
            const strIsWarnNote = apps.getStorageSync("strIsWarnNote") || "N";
            const authors = uni.getAppAuthorizeSetting();
            console.log(JSON.stringify(authors));
            if (authors && authors.notificationAuthorized != 'authorized') {
                notificationStatus.value = false;
                if (strIsWarnNote == "N") {
                    uni.showModal({
                        content: '【管e通】通知未开启，是否前往系统设置开启？开启后重登管e通生效！',
                        confirmColor: '#01B0C6',
                        confirmText: '去设置',
                        success: function(e) {
                            if (e.confirm) {
                                permManager.gotoAppPermissionSetting();
                            }
                            apps.setStorageSync("strIsWarnNote", "Y");
                        }
                    })
                }

            } else {
                notificationStatus.value = true;
            }
        } catch (ex) {
            apps.setStorageSync("strIsWarnNote", "Y");
            notificationStatus.value = true;
        }

        const CUSTOMEROBJECT = service.getStorageSync("CUSTOMEROBJECT");
        let customerObject = CUSTOMEROBJECT ? CUSTOMEROBJECT : {};

        if (customerObject && customerObject.ID) {
            var customerNo = customerObject.ID;
            if(customerNo!='EIInnerNet') {
                const AmapArray = service.getStorageSync('MobileAmap');
                const ObjectData = {
                    IsNotPage: true,
                    SqlWhereTail: " where c_cloud_id = '" + customerNo + "' ",
                    Tag: AmapArray
                }
                apps.GetCloudCustDef(ObjectData, (res) => {
                    service.setStorageSync('MobileAmap',JSON.stringify([]))
                    if(!res.HasException) {
                        //加载成功后重新缓存配置信息
                        ReStoreCloudInfo(res.ObjectData);
                    } else{
                        uni.showToast({
                            title: `获取客户配置失败，原因：${res.Exception?.Message}`,
                            duration: 3500,
                            icon: 'none',
                        })
                    }
                },(err) => {
                    uni.showToast({
                        title: `获取客户配置失败-Index!`,
                        duration: 3500,
                        icon: 'none',
                    })
                    //客户代码加载失败时的处理，一般是网络等原因，这种情况下忽略失败，判断原来缓存的配置是否可用，可用则直接用原来的缓存内容
                    VerUpdate();
                });

            } else {
                service.setStorageSync("MobileAmap", JSON.stringify([]));
                //若是离线的配置直接调用查询
                VerUpdate();
            }
        } else {
            uni.reLaunch({
                url: '../reg/reg'
            });
        }
    })

    const moduleDataStore = useModuleDataStore();
    const GetMyMenu = () => {
        let request = {
            url: LoginStore.EnjoyMain,
            data: {
                UniqueKey: "管易通40公共",
                ObjectData: mainStore.loginInfo?.sUser && mainStore.loginInfo?.sUser != '' && mainStore.loginInfo?.sUser !=
                    null ? mainStore.loginInfo?.sUser : '0720', //用于苹果审核特殊处理获取不到用户时默认按0006账号获取
                MethodName: "GetMyMenu",
            },
        }
        service.request(request, (res) => {
            if (res && res.data) {
                if (!res.data.HasException) {
                    const menus = res.data.ObjectData || [];
                    moduleDataStore.setMenusAndLimitCode(menus);
                } else {
                    service.enjoyShowToast(res.data.Exception.Message)
                }
            }
        }, () => {
            console.log('失败')
        });
    }

</script>

<style scoped lang="scss">
    .content {
        position: relative;
        width: 100%;
        height: 100vh;
        font-family: PingFangSC, PingFang SC;
        background: linear-gradient( 180deg, #EEF4FF 0%, #F0F5FF 92%, #F2F2F2 100%);
    }
    .top-bgc {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 160px;
        background-image: url('@/static/img/homeImgs/start_top.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: top left;
    }
    .main {
        position: absolute;
        top: 144px;
        left:  33px;
        .title {
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 26px;
            color: #333333;
        }
        .describe {
            color: #888888;
            font-size: 15px;
            font-weight: 400;
        }
    }
    .bottom-bgc {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 480px;
        background-image: url('@/static/img/homeImgs/start_main.png');
        background-size: 100% 480px;
        background-repeat: no-repeat;
    }

</style>
